using System;
using System.Diagnostics;
using OFX.Aggregator.Infrastructure;
using OFX.Aggregator.WebScraping.Infrastructure;

namespace OFX.Aggregator.WebScraping.Implementation.BESnet.HtmlPageProcessing
{
	public class BESnetPasswordPageProcessor : IHtmlPageProcessor
	{
		#region Implementation of IHtmlPageProcessor

		public void TestAssumptions(StatementSource source, IWebBrowser webBrowser)
		{
			IHtmlDocument document = webBrowser.Document;

			IHtmlElement bt0 = document.GetElementById("bt0");
			if (bt0 == null || bt0.TagName != "TD")
			{
				throw new AssumptionFailedException(this, "Expected 'bt0' element not found in page!");
			}
		}

		public void ProcessPage(StatementSource source, IWebBrowser webBrowser, IHtmlPageProcessorFinished finished)
		{
			IHtmlDocument document = webBrowser.Document;

			IHtmlElement bt0 = document.GetElementById("bt0");

			Debug.WriteLine(bt0.InnerText);

			string password = GetPassword(source);
			int offset = '0' - bt0.InnerText[0];
			foreach (char code in password)
			{
				PressPasswordButton(document, code, offset);
			}
		}

		#endregion

		private static string GetPassword(StatementSource source)
		{
			return source.Parameters["AccountPassword"];
		}

		private static void PressPasswordButton(IHtmlDocument document, char code, int offset)
		{
			const int numBase = 10;
			string param = Convert.ToString((code - '0' + offset + numBase)%numBase, numBase);

			document.InvokeScript("pK", new object[] {param});
		}
	}
}